import { forwardRef, useImperativeHandle, useState } from 'react';

import { useRequest } from 'ahooks';
import {
  Button,
  DatePicker,
  Drawer,
  Form,
  FormProps,
  Input,
  InputNumber,
  Radio,
  Select,
  Space
} from 'antd';
import dayjs from 'dayjs';
import { map } from 'lodash-es';

import { store } from '@/store';

import { orgUserInfoVoPage } from '@/services/base/yonghuguanlixitongyonghujiekou';
import { proInspectionPointList } from '@/services/bizApi/shengchanxunjiandiweijiekou';
import {
  proInspectionTaskAdd,
  proInspectionTaskUpdate
} from '@/services/bizApi/shengchanxunjianrenwujiekou';
import { ProFormSelect } from '@ant-design/pro-form';

import { BizObject } from './';

type EditOpenBaseArgs = {
  /** 成功回调 */
  onSuccess?: () => void;
};

export type EditRef = {
  open: (
    arg:
      | (EditOpenBaseArgs & {
          type: 'add';
        })
      | (EditOpenBaseArgs & {
          type: 'edit';
          rowData: BizObject;
        })
      | (EditOpenBaseArgs & {
          type: 'detail';
          rowData: BizObject;
        })
  ) => void;
};

export type EditProps = {};

const Edit: React.ForwardRefRenderFunction<EditRef, EditProps> = (_, ref) => {
  const [form] = Form.useForm();
  // 弹窗开启状态
  const [open, setOpen] = useState(false);
  const [args, setArgs] = useState<ArgumentsType<EditRef['open']>[0]>();
  const [inspectionUserName, setInspectionUserName] = useState<string[]>([]);
  // const [pointName, setPointName] = useState<string[]>([]);

  const submit = useRequest(
    async ({ _type, ...values }) => {
      const query = {
        ...values,
        taskId: args?.type === 'edit' ? args?.rowData?.taskId : undefined,
        taskStartTime: dayjs(values.taskStartTime).format('YYYY-MM-DD'),
        // pointName: pointName,
        pointId: values.pointId.join(','),
        inspectionUserId: values.inspectionUserId.join(','),
        inspectionUserName: inspectionUserName.join(',')
      };

      if (args?.type === 'add') {
        await proInspectionTaskAdd(query);
      } else {
        await proInspectionTaskUpdate(query);
      }
      args?.onSuccess?.();
      setOpen(false);

      store.app?.message.success(args?.type === 'add' ? '新增成功' : '编辑成功');
    },
    {
      manual: true
    }
  );

  useImperativeHandle(ref, () => {
    return {
      open: (arg) => {
        setArgs(arg);
        setOpen(true);

        // 编辑回填数据
        if ((arg?.type === 'edit' || arg?.type === 'detail') && arg?.rowData) {
          // 回填数据
          form.setFieldsValue({
            ...arg.rowData,
            taskStartTime: dayjs(arg.rowData.taskStartTime),
            inspectionUserId: arg?.rowData.inspectionUserId!.split(','),
            pointId: arg?.rowData.pointId!.split(',')
          });

          // setPointName(arg?.rowData.pointName);
          setInspectionUserName(arg?.rowData!.inspectionUserName?.split(',') as string[]);
        } else {
          form.resetFields();
        }
      }
    };
  });

  const onFinish: FormProps['onFinish'] = async (values) => {
    return submit.runAsync(values);
  };

  const onCancel = () => {
    if (submit.loading) {
      store.app?.message.info('正在提交中，请稍后');
      return;
    }
    setOpen(false);
  };

  // 仅保存
  const onSave = () => {
    form.submit();
  };

  return (
    <Drawer
      title={
        {
          add: '新增巡检任务',
          edit: '编辑巡检任务',
          detail: '详情'
        }[args?.type as string]
      }
      extra={
        <>
          {args?.type !== 'detail' && (
            <Space>
              <Button
                type="primary"
                loading={submit.loading}
                disabled={submit.loading}
                onClick={onSave}
              >
                确定
              </Button>
              <Button onClick={onCancel} disabled={submit.loading}>
                取消
              </Button>
            </Space>
          )}
        </>
      }
      width="50%"
      open={open}
      onClose={onCancel}
    >
      <Form
        onFinish={onFinish}
        form={form}
        layout="horizontal"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 14 }}
        disabled={args?.type === 'detail'}
        requiredMark={args?.type !== 'detail'}
        variant={args?.type === 'detail' ? 'borderless' : undefined}
      >
        <Form.Item
          label="任务名称"
          name="taskName"
          rules={[
            {
              required: true,
              message: '请输入任务名称'
            }
          ]}
        >
          <Input style={{ width: '100%' }} placeholder="请输入任务名称" />
        </Form.Item>

        <ProFormSelect
          name="inspectionUserId"
          label="巡检人员"
          placeholder="请选择巡检人员"
          mode="multiple"
          onChange={(_a, b) => {
            setInspectionUserName(map(b, 'label'));
          }}
          showSearch={true}
          rules={[{ required: true, message: '请选择巡检人员' }]}
          request={async () => {
            const res = await orgUserInfoVoPage({
              page: 1,
              size: 1000
            });

            return (
              res?.data?.records?.map((item) => {
                return {
                  label: item?.fullName,
                  value: item?.id
                };
              }) || []
            );
          }}
        />

        <ProFormSelect
          name="pointId"
          label="巡检点位"
          placeholder="请选择巡检点位"
          mode="multiple"
          // onChange={(_a, b) => {
          //   setPointName(map(b, 'label'));
          // }}
          showSearch={true}
          rules={[{ required: true, message: '请选择巡检点位' }]}
          request={async () => {
            const res = await proInspectionPointList({});
            return (
              res?.data?.map((item) => {
                return {
                  label: item?.pointName,
                  value: item?.pointId
                };
              }) || []
            );
          }}
        />

        <Form.Item
          label="任务执行周期"
          name="cycle"
          rules={[
            {
              required: true,
              message: '请选择任务执行周期'
            }
          ]}
        >
          <Select
            style={{ width: '100%' }}
            placeholder="请选择巡检周期"
            options={[
              {
                value: 1,
                label: '单次'
              },
              {
                value: 2,
                label: '时'
              },
              {
                value: 3,
                label: '日'
              }
            ]}
          />
        </Form.Item>
        <Form.Item dependencies={['cycle']} noStyle>
          {({ getFieldValue }) => {
            const cycle = getFieldValue(['cycle']);
            if (cycle === 2) {
              return (
                <Form.Item
                  label="巡检任务周期"
                  name="cycleValue"
                  rules={[
                    {
                      required: true,
                      message: '请选择巡检任务周期'
                    }
                  ]}
                >
                  <InputNumber
                    min={1}
                    max={24}
                    style={{ width: '100%' }}
                    placeholder="请选择巡检任务周期"
                    suffix="时"
                  />
                </Form.Item>
              );
            } else if (cycle === 3) {
              return (
                <Form.Item
                  label="巡检任务周期"
                  name="cycleValue"
                  rules={[
                    {
                      required: true,
                      message: '请选择巡检任务周期'
                    }
                  ]}
                >
                  <InputNumber
                    min={1}
                    max={31}
                    style={{ width: '100%' }}
                    placeholder="请选择巡检任务周期"
                    suffix="天"
                  />
                </Form.Item>
              );
            }
          }}
        </Form.Item>
        <Form.Item
          label="巡检任务开始日期"
          name="taskStartTime"
          rules={[
            {
              required: true,
              message: '请选择巡检任务开始日期'
            }
          ]}
        >
          <DatePicker
            format="YYYY-MM-DD"
            style={{ width: '100%' }}
            placeholder="请选择巡检任务开始日期"
          />
        </Form.Item>
        <Form.Item
          label="是否启用"
          name="status"
          rules={[
            {
              required: true,
              message: '请选择是否启用'
            }
          ]}
        >
          <Radio.Group>
            <Radio value={true}>启用</Radio>
            <Radio value={false}>停用</Radio>
          </Radio.Group>
        </Form.Item>
      </Form>
    </Drawer>
  );
};

export default forwardRef(Edit);
